package com.eco.fishway.service;

import io.minio.GetPresignedObjectUrlArgs;
import io.minio.ListObjectsArgs;
import io.minio.MinioClient;
import io.minio.Result;
import io.minio.http.Method;
import io.minio.messages.Item;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * @author: xulinyu
 * Created at: 2024/8/5 14:52
 */
@Service
@Slf4j
public class MinioService {

    private final MinioClient minioClient;


    public MinioService(MinioClient minioClient) {
        this.minioClient = minioClient;
    }


    public List<String> listObjects(String bucketName) {
        List<String> objectUrls = new ArrayList<>();

        try {
            //递归查询所有文件地址
            Iterable<Result<Item>> results = minioClient.listObjects(ListObjectsArgs.builder().recursive(true).bucket(bucketName).build());

            for (Result<Item> result : results) {
                Item item = result.get();
                String objectUrl = minioClient.getPresignedObjectUrl(
                        GetPresignedObjectUrlArgs.builder()
                                .bucket(bucketName)
                                .object(item.objectName())
                                .method(Method.GET)
                                .build()
                );
                objectUrls.add(objectUrl);
            }
        } catch (Exception e) {
            // 处理异常
            log.error(e.getMessage());
        }

        return objectUrls;
    }
}
